from rest_framework import serializers

from users.models import User
from .models import OAuthQQuser
from django_redis import get_redis_connection


class QQTokenSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)

    def validate(self, attrs):
        access_token = attrs.get('access_token')
        openid = OAuthQQuser.openid_by_token(access_token)
        if openid is None:
            raise serializers.ValidationError('openid发生错误')
        attrs['openid'] = openid

        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code is None:
            raise serializers.ValidationError('短信验证码已过期')
        sms_code = attrs.get('sms_code')
        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码不一致')

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            password = attrs.get('password')
            if not user.check_password(password):
                raise serializers.ValidationError('密码输入错误')
            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        # 1. 获取用户信息
        user = validated_data.get('user')
        # 2. 判断用户信息是否存在
        if user is None:
            # 不存在就创建
            user = User.objects.create(
                username=validated_data.get('mobile'),
                password=validated_data.get('password'),
                mobile=validated_data.get('mobile')
            )

            # 密码还是明文
            user.set_password(validated_data['password'])
            user.save()

        OAuthQQuser.objects.create(
            user=user,
            openid=validated_data.get('openid')
        )

        return user
